﻿//Copyright (c) 2009, Offbeat Guides
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other materials 
//provided with the distribution.
//
//* Neither the name of Offbeat Guides nor the names of its contributors may be used to 
//endorse or promote products derived from this software without specific prior written 
//permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
//OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
//TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.Reflection;
using System.IO;

namespace Amazon.Services.S3
{
    public class S3Configuration : Amazon.Services.IServiceConfiguration
    {
        #region Static Variables
        public static readonly S3Configuration Default;

        private static readonly Encoding Encoding = new UTF8Encoding();
        private static readonly MethodInfo DateMethodHack;
        #endregion

        #region IAmazonConfig Properties
        public String ServiceVersion { get; set; }

        public String SignatureMethod { get; set; }

        public String SignatureVersion { get; set; }

        public String UserAgent { get; set; }

        public String ServiceUrl { get; set; }

        public String ProxyHost { get; set; }

        public Int32 ProxyPort { get; set; }

        public Int32 MaxErrorRetry { get; set; }
        #endregion

        #region Constructors and Finalizers
        static S3Configuration()
        {
            S3Configuration.Default = new S3Configuration();
            S3Configuration.Default.ServiceVersion = "2006-03-01";
            S3Configuration.Default.ServiceUrl = "https://s3.amazonaws.com";
            S3Configuration.Default.UserAgent = "Offbeat S3 Library";
            S3Configuration.Default.SignatureVersion = "2";
            S3Configuration.Default.SignatureMethod = "HMACSHA1";
            S3Configuration.Default.ProxyHost = null;
            S3Configuration.Default.ProxyPort = -1;
            S3Configuration.Default.MaxErrorRetry = 3;

            S3Configuration.DateMethodHack = typeof(WebHeaderCollection).GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
        }
        #endregion

        #region Methods
        private String GenerateUrl(IDictionary<String, String> parameters)
        {
            String url = S3Configuration.Default.ServiceUrl;
            if (parameters.ContainsKey("bucket") && parameters.ContainsKey("path"))
                url = String.Format("{0}/{1}/{2}", url, parameters["bucket"], parameters["path"]);
            else if (parameters.ContainsKey("bucket"))
                url = String.Format("{0}/{1}", url, parameters["bucket"]);

            String queryString = String.Empty;
            if(parameters.ContainsKey("max-keys"))
                queryString += "max-keys=" + parameters["max-keys"];
            if(parameters.ContainsKey("marker"))
                queryString += "marker=" + parameters["marker"];
            if(parameters.ContainsKey("prefix"))
                queryString += "prefix=" + parameters["prefix"];
            if (parameters.ContainsKey("delimiter"))
                queryString += "delimiter=" + parameters["delimiter"];

            if (!String.IsNullOrEmpty(queryString))
                return String.Format("{0}?{1}", url, queryString);
            return url;
        }

        private String GenerateSignature(String method, String key, IDictionary<String, String> parameters)
        {
            KeyedHashAlgorithm algorithm = new HMACSHA1();
            String data = null;
            switch (this.SignatureVersion)
            {
                case "2":
                    algorithm = KeyedHashAlgorithm.Create(this.SignatureMethod);
                    data = this.CalculateSignature(method, parameters);
                    break;
                default:
                    throw new Exception("Invalid Signature Version specified");
            }

            algorithm.Key = S3Configuration.Encoding.GetBytes(key);
            Byte[] buffer = S3Configuration.Encoding.GetBytes(data.ToCharArray());
            buffer = algorithm.ComputeHash(buffer);
            return Convert.ToBase64String(buffer);
        }

        private String CalculateSignature(String method, IDictionary<String, String> parameters)
        {
            IDictionary<String, String> sortedParameters = new SortedDictionary<String, String>(parameters, StringComparer.Ordinal);

            String amzHeaders = String.Empty;
            foreach (String key in sortedParameters.Keys)
            {
                if (key.StartsWith("x-amz-", StringComparison.OrdinalIgnoreCase))
                    amzHeaders += String.Format("{0}:{1}\n", key.ToLower().Trim(), sortedParameters[key].Trim());
            }

            String resource = "/";
            if (parameters.ContainsKey("bucket") && parameters.ContainsKey("path"))
                resource = String.Format("/{0}/{1}", parameters["bucket"], parameters["path"]);
            else if (parameters.ContainsKey("bucket"))
                resource = String.Format("/{0}", parameters["bucket"]);

            return String.Format("{0}\n{1}\n{2}\n{3}\n{4}{5}",
                method,
                sortedParameters.ContainsKey("content-md5") ? sortedParameters["content-md5"] : String.Empty,
                sortedParameters.ContainsKey("content-type") ? sortedParameters["content-type"] : String.Empty,
                sortedParameters["date"],
                amzHeaders,
                resource);
        }
        #endregion

        #region IServiceConfiguration Methods
        public WebRequest CreateRequest(AmazonAccount account, IDictionary<String, String> parameters, Byte[] contents)
        {
            if(!parameters.ContainsKey("date"))
                parameters.Add("date", DateTime.UtcNow.ToString("r"));

            String signature = this.GenerateSignature(parameters.ContainsKey("method") ? parameters["method"] : "GET", account.SecretKey, parameters);
            signature = String.Format("AWS {0}:{1}", account.Key, signature);

            HttpWebRequest request = WebRequest.Create(this.GenerateUrl(parameters)) as HttpWebRequest;
            S3Configuration.DateMethodHack.Invoke(request.Headers, new[] { "Date", parameters["date"] });
            request.UserAgent = S3Configuration.Default.UserAgent;
            request.Headers.Add("Authorization", signature);
            request.Method = parameters.ContainsKey("method") ? parameters["method"] : "GET";
            request.Timeout = 300000;

            foreach (String key in parameters.Keys)
            {
                if (key.StartsWith("x-amz-", StringComparison.OrdinalIgnoreCase))
                    request.Headers.Add(key.ToLower().Trim(), parameters[key].Trim());
            }

            // if a proxy host is defined, then use it for requests.
            if (!String.IsNullOrEmpty(S3Configuration.Default.ProxyHost))
                request.Proxy = new WebProxy(S3Configuration.Default.ProxyHost, S3Configuration.Default.ProxyPort);

            // if content is defined then write it out to the stream
            if (contents != null)
            {
                request.ContentType = parameters["content-type"];
                request.ContentLength = contents.Length;

                using (Stream stream = request.GetRequestStream())
                    stream.Write(contents, 0, contents.Length);
            }

            return request;
        }
        #endregion
    }
}
